//
//  QJMineOrderPageVC.m
//  QuanJieShopProject
//
//  Created by 刘中义 on 2018/2/24.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJMineOrderPageVC.h"
#import "HTopView.h"
//数据为空
#import "UIScrollView+EmptyDataSet.h"
#import "QJMineOrderHeader.h"
#import "QJPreviewOrderCell.h"
#import "QJMineOrderFooter.h"
#import "QJMineOrderFooterTwo.h"
#import "QJMineOrderFooterThree.h"
#import "QJMineOrderFooterFourth.h"
//去付款
#import "QJOrderPayVC.h"
#import "YFLogisticsViewController.h"
#import "QJOrderPayVC.h"
#import "QJPreviewOrderDetailVC.h"
#import "QJOrderDetailVC.h"
@interface QJMineOrderPageVC () <UITableViewDelegate,UITableViewDataSource,HTopViewDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UIScrollViewDelegate>
{
    NSInteger topBtnTag;
}

@property (nonatomic, strong) UITableView *orderTableView;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) HTopView *hTopView;
@property (nonatomic, copy) NSString *pay_status;
@property (nonatomic, copy) NSString *shipping_status;
@property (nonatomic, strong)NSDictionary *profit;
@property (nonatomic, assign)NSInteger pageNum;
@end

@implementation QJMineOrderPageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupOrderUIAction];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setNavAlpha:YES];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
    self.navigationController.navigationBar.translucent = YES;
}
#pragma mark -- 界面布局
- (void)setupOrderUIAction{
    self.title = @"我的订单";
    HTopView *topView = [[HTopView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 40)];
    self.hTopView = topView;
    [self.view addSubview:topView];
    [topView setGesture:self.view];
    topView.backgroundColor = [UIColor whiteColor];
    topView.delegate = self;
    topView.btnTitleClolor = YFColor_Text;
    topView.btnSelectClolor = YFColor_Red;
    topView.lineColor = YFColor_Red;
    NSMutableArray *topArray = [NSMutableArray arrayWithObjects:@"全部",@"待付款",@"待发货",@"已发货",@"已完成",nil];
    topView.btnArray = topArray;
    [topView setUI];
    
    self.orderTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 42, UISCREEN_WIDTH, UISCREEN_HEIGHT - 42 - 64) style:UITableViewStyleGrouped];
    [self.view addSubview:self.orderTableView];
    self.orderTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.orderTableView.delegate = self;
    self.orderTableView.dataSource = self;
    self.orderTableView.backgroundColor = [UIColor whiteColor];
    self.orderTableView.emptyDataSetDelegate = self;
    self.orderTableView.emptyDataSetSource = self;
   
    //注册区头
    [self.orderTableView registerClass:[QJMineOrderHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    //注册区尾
    [self.orderTableView registerNib:[UINib nibWithNibName:@"QJMineOrderFooter" bundle:nil] forHeaderFooterViewReuseIdentifier:@"footer"];
    [self.orderTableView registerNib:[UINib nibWithNibName:@"QJMineOrderFooterTwo" bundle:nil] forHeaderFooterViewReuseIdentifier:@"footerTwo"];
    [self.orderTableView registerNib:[UINib nibWithNibName:@"QJMineOrderFooterThree" bundle:nil] forHeaderFooterViewReuseIdentifier:@"footerThree"];
     [self.orderTableView registerNib:[UINib nibWithNibName:@"QJMineOrderFooterFourth" bundle:nil] forHeaderFooterViewReuseIdentifier:@"footerFour"];
    self.orderTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HRefresh)];
    self.orderTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(FRefresh)];
    //设置进来选中的界面
    [topView tagBtnClick:self.htopViewBtnTag];
    //解决表无故偏移
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.pay_status = @"0";
    self.shipping_status = @"0";
}

#pragma mark -- 刷新加载方法
- (void)HRefresh{
    self.pageNum = 1;
    [self orderDataRequestAction];
}
- (void)FRefresh{
    self.pageNum++;
   [self orderDataRequestAction];
}
- (void)orderDataRequestAction{
    // 老接口: 对应status 全部订单：0，1：待付款，2：待发货，3：已发货，4：已完成
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    // 新接口: 根据不同status, 拼接不同的参数
    if (topBtnTag == 0) {
//        dict = nil;
         self.pay_status = @"0";
    }else if (topBtnTag == 1) {  // 待付款
        [dict setObject:@"0" forKey:@"pay_status"];
        self.pay_status = @"1";
    }else if (topBtnTag == 2) {  // 待发货
        [dict setObject:@"1" forKey:@"pay_status"];
        [dict setObject:@"0" forKey:@"shipping_status"];
         self.pay_status = @"2";
    }else if (topBtnTag == 3) {  // 已发货
        [dict setObject:@"1" forKey:@"pay_status"];
        [dict setObject:@"1" forKey:@"shipping_status"];
         self.pay_status = @"3";
    }else if (topBtnTag == 4) {  // 已完成
        [dict setObject:@"4" forKey:@"order_status"];
         self.pay_status = @"4";
    }
    
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.pageNum] forKey:@"p"];
   
    NSLog(@"订单列表 dict = %@", dict);
 
    [WWNetRequest fetchOrderListWithParameters:dict success:^(id response) {
        NSLog(@"订单列表 response = %@", response);
        NSMutableArray *array = [NSMutableArray array];
        NSArray *dataArr = response[@"0"][@"order_list"];
        NSDictionary *profit = response[@"0"][@"profit"];
        for (NSDictionary *dict in dataArr) {
            // 店铺信息
            MineOrderModel *model = [[MineOrderModel alloc] initWithDictionary:dict error:nil];
            if ([[dict objectForKey:@"goods_list"] isKindOfClass:[NSArray class]]) {
                NSArray *goodsArr = [dict objectForKey:@"goods_list"];
                NSMutableArray *subArr = [NSMutableArray array];
                for (NSDictionary *detailDict in goodsArr) {
                    MineOrderDetailModel *detailModel = [[MineOrderDetailModel alloc] initWithDictionary:detailDict error:nil];
                    detailModel.order_status_desc = [dict objectForKey:@"order_status_desc"];
                    detailModel.profit = profit;
                    [subArr addObject:detailModel];
                }
                model.detailArr = subArr;
                [array addObject:model];
                
            }
        }
        
        if (self.pageNum == 1) {
            [self.sectionArray removeAllObjects];
            self.sectionArray = array;
        }else{
            if (array.count == 0) {
                [self.orderTableView.mj_footer endRefreshingWithNoMoreData];
            }
            for (MineOrderModel *model in array) {
                [self.sectionArray addObject:model];
            }
        }
       
        [self.orderTableView reloadData];
        
        [self.orderTableView.mj_header endRefreshing];
        [self.orderTableView.mj_footer endRefreshing];
        
    } failure:^(NSDictionary *error) {
        NSLog(@"订单列表 error = %@", error);

        [self.sectionArray removeAllObjects];
        [self.orderTableView reloadData];
        [self.orderTableView.mj_header endRefreshing];
         [self.orderTableView.mj_footer endRefreshing];
    }];
    
}


#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    MineOrderModel *model = self.sectionArray[section];
    return model.detailArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    QJPreviewOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QJPreviewOrderCell" owner:self options:nil] lastObject];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    MineOrderModel *model = self.sectionArray[indexPath.section];
    MineOrderDetailModel *detailModel = model.detailArr[indexPath.row];
    [cell cellUpdateWithMineOrderDetailModel:detailModel];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  
    MineOrderModel *model =  (MineOrderModel *)[self.sectionArray objectAtIndex:indexPath.section];
    QJOrderDetailVC *vc = [[QJOrderDetailVC alloc]init];
    vc.orderID = model.order_id;
    [self.navigationController pushViewController:vc animated:YES];
    
}

// 返回区头的高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}
// 返回foot的高
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
   
    if([self.pay_status isEqualToString:@"2"]){
        
        return 40;
    }
    
    return 85;
}
// 注册区头
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    QJMineOrderHeader *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    [headerView headerUpdateModel:self.sectionArray[section]];
    return headerView;
}
// 注册区尾
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    WEAKSELF
    MineOrderModel *model = self.sectionArray[section];
    NSString *statusStr = self.pay_status;

    if ([statusStr isEqualToString:@"0"]) {  // 全部
        
        QJMineOrderFooterTwo *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerTwo"];
        [footerView footerUpdateModel:model payStatus:statusStr];
        typeof(footerView) __weak weakFooterView = footerView;
        
        footerView.cancelOrderBlcokAction = ^(MineOrderModel *model) { // 取消订单
            NSLog(@" 取消订单");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:model.order_id forKey:@"order_id"];
            [WWNetRequest fetchCancelOrderWithParameters:dic success:^(id response) {
                NSLog(@"取消订单 response = %@", response);
                // 将按钮置灰
        
                [weakFooterView.button1 setTitle:@"已取消" forState:UIControlStateNormal];
                weakFooterView.button1.layer.borderColor = YFColor_Text.CGColor;
                [weakFooterView.button1 setTitleColor:YFColor_Text forState:UIControlStateNormal];
                weakFooterView.button2.hidden = YES;
                
            } failure:^(NSDictionary *error) {
                NSLog(@"取消订单 error = %@", error);
                
            }];
        };
        return footerView;
    }
    if ([statusStr isEqualToString:@"1"]) {  // 待付款
        QJMineOrderFooter *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footer"];
        [footerView footerUpdateModel:model status:self.pay_status];
       
        
        typeof(footerView) __weak weakFooterView = footerView;

        footerView.cancelOrderBlcokAction = ^(MineOrderModel *model) { // 取消订单
            NSLog(@" 取消订单");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:model.order_id forKey:@"order_id"];
            [WWNetRequest fetchCancelOrderWithParameters:dic success:^(id response) {
                NSLog(@"取消订单 response = %@", response);
                // 将按钮置灰
               
                weakFooterView.cancelOrder.layer.borderColor = YFColor_Text.CGColor;
                weakFooterView.gopayBtn.hidden = YES;
                
            } failure:^(NSDictionary *error) {
                NSLog(@"取消订单 error = %@", error);

            }];
        };
        
        footerView.deleteOrderBlcokAction = ^(MineOrderModel *model) {
            
            NSLog(@"删除订单");
            
            [WWNetRequest fetchDeleteOrderWithParameters:model.order_id success:^(id response) {
                
                NSLog(@"删除订单 response = %@", response);
                
            } failure:^(NSDictionary *error) {
                
                
                NSLog(@"删除订单 error = %@", error);
                
                
            }];
        };
        return footerView;
    }else if ([statusStr isEqualToString:@"2"]){//代发货
        
        
        QJMineOrderFooterTwo *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerTwo"];
        footerView.button1.hidden = YES;
        footerView.button2.hidden = YES;
        footerView.button3.hidden = YES;
        [footerView footerUpdateModel:model payStatus:statusStr];
        return footerView;
        
    }else if ([statusStr isEqualToString:@"3"]){//查看物流、确认收货
        
        
        
        QJMineOrderFooterThree *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerThree"];
        [footerView footerUpdateModel:model];
        return footerView;
        
        
    }
    
    else if ([statusStr isEqualToString:@"4"]){  // 已完成
        QJMineOrderFooterFourth *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"footerFour"];
        [footerView footerUpdateModel:model];
        
        return footerView;
        
    }
    
    return nil;
    
}
#pragma mark - htopViewDelegate
-(void)HTopViewBtnClick:(NSInteger)tag {
    KMyLog(@"第%ld界面请求数据",tag);
    topBtnTag = tag;
    //数据请求
    [self.orderTableView.mj_header beginRefreshing];
}
#pragma mark -- DZNEmptyDataSetSource
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"noDataImage"];
}
#pragma mark -- DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
#pragma mark -- 懒加载
-(NSMutableArray *)sectionArray{
    if (!_sectionArray) {
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}


@end
